import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

type Language = 'en' | 'zh';

interface LanguageContextType {
  language: Language;
  setLanguage: (language: Language) => void;
  t: (key: string) => string;
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export const useLanguage = () => {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
};

interface LanguageProviderProps {
  children: ReactNode;
}

// Translation dictionary
const translations = {
  en: {
    // Navigation
    'nav.home': 'Home',
    'nav.discover': 'Discover',
    'nav.community': 'Community',
    'nav.profile': 'Profile',
    'nav.getStarted': 'Get Started',
    'nav.language': 'Language',
    
    // Common buttons
    'btn.save': 'Save Changes',
    'btn.cancel': 'Cancel',
    'btn.edit': 'Edit',
    'btn.delete': 'Delete',
    'btn.viewDetails': 'View Details',
    'btn.getStarted': 'Get Started Free',
    'btn.watchDemo': 'Watch Demo',
    'btn.continueAsStudent': 'Continue as Student',
    'btn.continueAsTeacher': 'Continue as Teacher',
    'btn.editProfile': 'Edit Profile',
    'btn.startJourney': 'Start Your Journey',
    'btn.joinCommunity': 'Join Community',
    'btn.continueLearning': 'Continue Learning',
    'btn.exploreFeatures': 'Explore All Features',
    'btn.getRecommendations': 'Get Personalized Recommendations',
    
    // Role switcher
    'role.student': 'Student',
    'role.teacher': 'Teacher',
    'role.switchTo': 'Switch to {role} view',
    
    // Profile page
    'profile.title': 'Profile',
    'profile.selfAssessment': 'Self Assessment',
    'profile.myResources': 'My Resources',
    'profile.myFavorites': 'My Favorites',
    'profile.myGroups': 'My Groups',
    'profile.learningProfile': 'Learning Profile',
    'profile.learningStyle': 'Learning Style',
    'profile.personalityType': 'Personality Type',
    'profile.interestProfile': 'Interest Profile',
    'profile.keyStrengths': 'Key Strengths',
    'profile.quickStats': 'Quick Stats',
    'profile.activeProjects': 'Active Projects',
    'profile.savedResources': 'Saved Resources',
    'profile.groupMemberships': 'Group Memberships',
    'profile.creativeContributor': 'Creative Contributor',
    'profile.socialInvestigative': 'Social-Investigative',
    'profile.analytical': 'Analytical',
    'profile.creative': 'Creative',
    'profile.collaborative': 'Collaborative',
    'profile.visual': 'Visual',
    
    // Home page
    'home.hero.title': 'Transform Your Learning with AI Intelligence',
    'home.hero.subtitle': 'Discover personalized learning paths, connect with study partners, and unlock your potential with our AI-powered educational platform designed for modern learners.',
    'home.hero.aiPowered': 'AI-Powered Learning Platform',
    'home.features.title': 'Everything You Need to Excel',
    'home.features.subtitle': 'Our comprehensive platform provides all the tools and insights you need to accelerate your learning journey.',
    'home.features.toolMarket': 'Tool Market',
    'home.features.toolMarketDesc': 'Access a comprehensive marketplace of educational tools and resources designed to enhance your teaching and learning experience.',
    'home.features.pblWorkshop': 'PBL Case Workshop',
    'home.features.pblWorkshopDesc': 'Explore our Project-Based Learning workshop with real-world case studies and hands-on activities for immersive education.',
    'home.features.smartCourseware': 'Smart Courseware Assembly',
    'home.features.smartCoursewareDesc': 'AI-powered courseware assembly that automatically organizes and structures learning materials for optimal educational outcomes.',
    'home.features.adaptiveContent': 'Adaptive Content',
    'home.features.adaptiveContentDesc': 'Learning materials that adapt to your progress and understanding level in real-time.',
    'home.features.realTimeAnalytics': 'Real-time Analytics',
    'home.features.realTimeAnalyticsDesc': 'Track your progress with detailed insights and performance analytics to optimize your learning.',
    'home.features.aiSupport': '24/7 AI Support',
    'home.features.aiSupportDesc': 'Get instant help and guidance from our AI tutor whenever you need assistance.',
    'home.community.title': 'Join Our Learning Community',
    'home.community.subtitle': 'Connect with thousands of learners worldwide and accelerate your growth through collaborative learning.',
    'home.cta.title': 'Start Your Learning Journey Today',
    'home.cta.subtitle': 'Join thousands of successful learners who have transformed their education with Mevolution\'s AI-powered platform.',
    'home.needs.title': 'Tell Us About Your Needs',
    'home.needs.subtitle': 'Help us understand your specific requirements so we can provide personalized recommendations and solutions.',
    'home.needs.lookingFor': 'What are you looking for?',
    'home.needs.yourRole': 'Your Role',
    'home.needs.additionalInfo': 'Additional Information',
    'home.needs.placeholder': 'Tell us more about your specific needs, goals, or challenges...',
    'home.needs.templates': 'Educational templates and resources',
    'home.needs.pblGuidance': 'PBL project guidance',
    'home.needs.aiCourseCreation': 'AI-powered course creation',
    'home.needs.learningAnalytics': 'Learning analytics and insights',
    'home.needs.teacherEducator': 'Teacher/Educator',
    'home.needs.administrator': 'Administrator',
    'home.needs.contentCreator': 'Content Creator',
    'home.stats.activeLearners': 'Active Learners',
    'home.stats.successRate': 'Success Rate',
    'home.stats.userRating': 'User Rating',
    
    // Role selection
    'roleSelect.title': 'Choose Your Role',
    'roleSelect.subtitle': 'Select your role to get a personalized experience tailored to your needs.',
    'roleSelect.student.title': 'Student',
    'roleSelect.student.desc': 'Access learning resources and track your progress',
    'roleSelect.student.feature1': 'Personalized learning paths',
    'roleSelect.student.feature2': 'Progress tracking',
    'roleSelect.student.feature3': 'Community interaction',
    'roleSelect.student.feature4': 'Resource library access',
    'roleSelect.teacher.title': 'Teacher',
    'roleSelect.teacher.desc': 'Create content and manage your teaching resources',
    'roleSelect.teacher.feature1': 'Course creation tools',
    'roleSelect.teacher.feature2': 'Student management',
    'roleSelect.teacher.feature3': 'Analytics and insights',
    'roleSelect.teacher.feature4': 'Resource sharing',
    
    // Hero section
    'hero.title': 'Transform Your Learning with AI',
    'hero.subtitle': 'Discover your unique learning style, unlock your potential, and connect with a community of learners powered by artificial intelligence.',
    'hero.aiRevolution': 'AI-Powered Learning Revolution',
    'hero.aiInsights': 'AI-Powered Insights',
    'hero.aiInsightsDesc': 'Discover your learning patterns with advanced AI analysis',
    'hero.personalizedLearning': 'Personalized Learning',
    'hero.personalizedLearningDesc': 'Get customized paths tailored to your unique style',
    'hero.smartCommunity': 'Smart Community',
    'hero.smartCommunityDesc': 'Connect with compatible learners and study partners',

    // Modules
    'modules.title': 'Core Learning Modules',
    'modules.subtitle': 'Access powerful tools designed to enhance your teaching and learning experience.',
    'modules.resources.title': 'Teaching Resource Library',
    'modules.resources.description': 'Access structured repository of lesson plans, multimedia materials, and curriculum standards.',
    'modules.pbl.title': 'PBL Case Workshop',
    'modules.pbl.description': 'Explore ready-made case studies and create custom project-based learning experiences.',
    'modules.builder.title': 'Smart Lesson Builder',
    'modules.builder.description': 'Auto-generate lesson structures with AI-powered activity suggestions and assessments.',
    'modules.analytics.title': 'Learning Analytics',
    'modules.analytics.description': 'Visualize student engagement, progress, and performance metrics across your classes.',
    'modules.classroom.title': 'Classroom Management',
    'modules.classroom.description': 'Manage student profiles, attendance, groups, and class administration tools.',

    // Resources page
    'resources.title': 'Teaching Resource Library',
    'resources.subtitle': 'Discover comprehensive educational materials, lesson plans, and multimedia resources to enhance your teaching.',
    'resources.searchPlaceholder': 'Search resources by topic, grade, or subject...',
    'resources.filter': 'Filter',
    'resources.grade': 'Grade Level',
    'resources.subject': 'Subject',
    'resources.downloads': 'Downloads',
    'resources.download': 'Download',
    'resources.preview': 'Preview',
    'resources.shareTitle': 'Share Your Resources',
    'resources.shareSubtitle': 'Contribute to our community by sharing your teaching materials and help other educators.',
    'resources.uploadResource': 'Upload Resource',

    // PBL Workshop page
    'pbl.title': 'PBL Case Workshop',
    'pbl.subtitle': 'Explore project-based learning with real-world case studies and collaborative learning experiences.',
    'pbl.featured': 'Featured Case',
    'pbl.exploreCase': 'Explore This Case',
    'pbl.grade': 'Grade Level',
    'pbl.subject': 'Subject Area',
    'pbl.skills': 'Skills Developed',
    'pbl.views': 'views',
    'pbl.useCase': 'Use This Case',
    'pbl.createTitle': 'Create Your Own Case Study',
    'pbl.createSubtitle': 'Design custom PBL experiences tailored to your curriculum and share with the community.',
    'pbl.startCreating': 'Start Creating',

    // Smart Builder page
    'builder.title': 'Smart Lesson Builder',
    'builder.subtitle': 'Create comprehensive lesson plans with AI assistance and structured learning objectives.',
    'builder.lessonSetup': 'Lesson Setup',
    'builder.lessonTitle': 'Lesson Title',
    'builder.titlePlaceholder': 'Enter your lesson title...',
    'builder.subject': 'Subject Area',
    'builder.subjectPlaceholder': 'e.g., Biology, Mathematics, History',
    'builder.gradeLevel': 'Grade Level',
    'builder.duration': 'Duration',
    'builder.learningObjectives': 'Learning Objectives',
    'builder.objectivesPlaceholder': 'What should students learn from this lesson?',
    'builder.keyTopics': 'Key Topics & Concepts',
    'builder.topicsPlaceholder': 'List the main topics to cover...',
    'builder.generateLesson': 'Generate Lesson Plan',
    'builder.lessonPreview': 'Generated Lesson Preview',
    'builder.saveLesson': 'Save Lesson',
    'builder.shareLesson': 'Share',
    'builder.exportLesson': 'Export',
    'builder.templates': 'Lesson Templates',
    'builder.viewAllTemplates': 'View All Templates',

    // Analytics page
    'analytics.title': 'Learning Analytics',
    'analytics.subtitle': 'Track student progress, engagement, and performance with comprehensive analytics and insights.',
    'analytics.totalStudents': 'Total Students',
    'analytics.avgEngagement': 'Avg Engagement',
    'analytics.completionRate': 'Completion Rate',
    'analytics.avgTime': 'Avg Session Time',
    'analytics.classPerformance': 'Class Performance Overview',
    'analytics.students': 'students',
    'analytics.engagement': 'Engagement',
    'analytics.completion': 'Completion',
    'analytics.topPerformers': 'Top Performers',
    'analytics.skillsDevelopment': 'Skills Development Tracking',
    'analytics.criticalThinking': 'Critical Thinking',
    'analytics.collaboration': 'Collaboration',
    'analytics.problemSolving': 'Problem Solving',

    // Classroom page
    'classroom.title': 'Classroom Management',
    'classroom.subtitle': 'Manage your classes, students, and learning groups with comprehensive administration tools.',
    'classroom.addStudent': 'Add Student',
    'classroom.takeAttendance': 'Take Attendance',
    'classroom.sendMessage': 'Send Message',
    'classroom.classSettings': 'Class Settings',
    'classroom.myClasses': 'My Classes',
    'classroom.students': 'students',
    'classroom.active': 'Active',
    'classroom.attendance': 'Attendance',
    'classroom.assignments': 'Active Assignments',
    'classroom.viewClass': 'View Class',
    'classroom.contact': 'Contact',
    'classroom.recentActivity': 'Recent Student Activity',
    'classroom.learningGroups': 'Learning Groups',
    'classroom.manageGroups': 'Manage Groups',
    'classroom.quickStats': 'Quick Stats',
    'classroom.totalStudents': 'Total Students',
    'classroom.avgAttendance': 'Avg Attendance',
    'classroom.activeAssignments': 'Active Assignments',
  },
  zh: {
    // Navigation
    'nav.home': '首页',
    'nav.discover': '发现',
    'nav.community': '社区',
    'nav.profile': '个人资料',
    'nav.getStarted': '开始使用',
    'nav.language': '语言',
    
    // Common buttons
    'btn.save': '保存更改',
    'btn.cancel': '取消',
    'btn.edit': '编辑',
    'btn.delete': '删除',
    'btn.viewDetails': '查看详情',
    'btn.getStarted': '免费开始',
    'btn.watchDemo': '观看演示',
    'btn.continueAsStudent': '以学生身份继续',
    'btn.continueAsTeacher': '以教师身份继续',
    'btn.editProfile': '编辑个人资料',
    'btn.startJourney': '开始您的学习之旅',
    'btn.joinCommunity': '加入社区',
    'btn.continueLearning': '继续学习',
    'btn.exploreFeatures': '探索所有功能',
    'btn.getRecommendations': '获取个性化推荐',
    
    // Role switcher
    'role.student': '学生',
    'role.teacher': '教师',
    'role.switchTo': '切换到{role}视图',
    
    // Profile page
    'profile.title': '个人资料',
    'profile.selfAssessment': '自我评估',
    'profile.myResources': '我的资源',
    'profile.myFavorites': '我的收藏',
    'profile.myGroups': '我的小组',
    'profile.learningProfile': '学习档案',
    'profile.learningStyle': '学习风格',
    'profile.personalityType': '人格类型',
    'profile.interestProfile': '兴趣档案',
    'profile.keyStrengths': '核心优势',
    'profile.quickStats': '快速统计',
    'profile.activeProjects': '活跃项目',
    'profile.savedResources': '保存的资源',
    'profile.groupMemberships': '小组成员资格',
    'profile.creativeContributor': '创意贡献者',
    'profile.socialInvestigative': '社会-研究型',
    'profile.analytical': '分析型',
    'profile.creative': '创意型',
    'profile.collaborative': '协作型',
    'profile.visual': '视觉型',
    
    // Home page
    'home.hero.title': '用AI智能改变您的学习',
    'home.hero.subtitle': '发现个性化学习路径，与学习伙伴建立联系，通过我们专为现代学习者设计的AI驱动教育平台释放您的潜力。',
    'home.hero.aiPowered': 'AI驱动的学习平台',
    'home.features.title': '成功所需的一切',
    'home.features.subtitle': '我们的综合平台提供您加速学习旅程所需的所有工具和见解。',
    'home.features.toolMarket': '工具市场',
    'home.features.toolMarketDesc': '访问全面的教育工具和资源市场，旨在增强您的教学和学习体验。',
    'home.features.pblWorkshop': 'PBL案例工坊',
    'home.features.pblWorkshopDesc': '探索我们的项目式学习工坊，包含真实世界的案例研究和沉浸式教育的实践活动。',
    'home.features.smartCourseware': '智能组课件',
    'home.features.smartCoursewareDesc': 'AI驱动的课件组装，自动组织和构建学习材料以获得最佳教育成果。',
    'home.features.adaptiveContent': '自适应内容',
    'home.features.adaptiveContentDesc': '学习材料实时适应您的进度和理解水平。',
    'home.features.realTimeAnalytics': '实时分析',
    'home.features.realTimeAnalyticsDesc': '通过详细的见解和性能分析跟踪您的进度，优化您的学习。',
    'home.features.aiSupport': '24/7 AI支持',
    'home.features.aiSupportDesc': '随时从我们的AI导师那里获得即时帮助和指导。',
    'home.community.title': '加入我们的学习社区',
    'home.community.subtitle': '与全球数千名学习者建立联系，通过协作学习加速您的成长。',
    'home.cta.title': '今天开始您的学习之旅',
    'home.cta.subtitle': '加入数千名成功学习者的行列，他们已经通过Mevolution的AI驱动平台改变了他们的教育。',
    'home.needs.title': '告诉我们您的需求',
    'home.needs.subtitle': '帮助我们了解您的具体要求，以便我们能够提供个性化的推荐和解决方案。',
    'home.needs.lookingFor': '您在寻找什么？',
    'home.needs.yourRole': '您的角色',
    'home.needs.additionalInfo': '其他信息',
    'home.needs.placeholder': '告诉我们更多关于您的具体需求、目标或挑战...',
    'home.needs.templates': '教育模板和资源',
    'home.needs.pblGuidance': 'PBL项目指导',
    'home.needs.aiCourseCreation': 'AI驱动的课程创建',
    'home.needs.learningAnalytics': '学习分析和见解',
    'home.needs.teacherEducator': '教师/教育工作者',
    'home.needs.administrator': '管理员',
    'home.needs.contentCreator': '内容创作者',
    'home.stats.activeLearners': '活跃学习者',
    'home.stats.successRate': '成功率',
    'home.stats.userRating': '用户评分',
    
    // Role selection
    'roleSelect.title': '选择您的角色',
    'roleSelect.subtitle': '选择您的角色以获得量身定制的个性化体验。',
    'roleSelect.student.title': '学生',
    'roleSelect.student.desc': '访问学习资源并跟踪您的进度',
    'roleSelect.student.feature1': '个性化学习路径',
    'roleSelect.student.feature2': '进度跟踪',
    'roleSelect.student.feature3': '社区互动',
    'roleSelect.student.feature4': '资源库访问',
    'roleSelect.teacher.title': '教师',
    'roleSelect.teacher.desc': '创建内容并管理您的教学资源',
    'roleSelect.teacher.feature1': '课程创建工具',
    'roleSelect.teacher.feature2': '学生管理',
    'roleSelect.teacher.feature3': '分析和见解',
    'roleSelect.teacher.feature4': '资源分享',
    
    // Hero section
    'hero.title': '用AI改变您的学习',
    'hero.subtitle': '发现您独特的学习风格，释放您的潜力，与由人工智能驱动的学习者社区建立联系。',
    'hero.aiRevolution': 'AI驱动的学习革命',
    'hero.aiInsights': 'AI驱动的见解',
    'hero.aiInsightsDesc': '通过先进的AI分析发现您的学习模式',
    'hero.personalizedLearning': '个性化学习',
    'hero.personalizedLearningDesc': '获得适合您独特风格的定制路径',
    'hero.smartCommunity': '智能社区',
    'hero.smartCommunityDesc': '与兼容的学习者和学习伙伴建立联系',

    // Modules
    'modules.title': '核心学习模块',
    'modules.subtitle': '访问专为增强您的教学和学习体验而设计的强大工具。',
    'modules.resources.title': '教学资源库',
    'modules.resources.description': '访问结构化的课程计划、多媒体材料和课程标准存储库。',
    'modules.pbl.title': 'PBL案例工坊',
    'modules.pbl.description': '探索现成的案例研究，创建定制的项目式学习体验。',
    'modules.builder.title': '智能组课件',
    'modules.builder.description': '使用AI驱动的活动建议和评估自动生成课程结构。',
    'modules.analytics.title': '学习分析',
    'modules.analytics.description': '可视化学生参与度、进度和跨班级绩效指标。',
    'modules.classroom.title': '班级管理',
    'modules.classroom.description': '管理学生档案、出勤、小组和班级管理工具。',

    // Resources page
    'resources.title': '教学资源库',
    'resources.subtitle': '发现全面的教育材料、课程计划和多媒体资源，以增强您的教学。',
    'resources.searchPlaceholder': '按主题、年级或学科搜索资源...',
    'resources.filter': '筛选',
    'resources.grade': '年级',
    'resources.subject': '学科',
    'resources.downloads': '下载次数',
    'resources.download': '下载',
    'resources.preview': '预览',
    'resources.shareTitle': '分享您的资源',
    'resources.shareSubtitle': '通过分享您的教学材料为我们的社区做出贡献，帮助其他教育工作者。',
    'resources.uploadResource': '上传资源',

    // PBL Workshop page
    'pbl.title': 'PBL案例工坊',
    'pbl.subtitle': '通过真实世界的案例研究和协作学习体验探索项目式学习。',
    'pbl.featured': '精选案例',
    'pbl.exploreCase': '探索此案例',
    'pbl.grade': '年级',
    'pbl.subject': '学科领域',
    'pbl.skills': '技能发展',
    'pbl.views': '浏览次数',
    'pbl.useCase': '使用此案例',
    'pbl.createTitle': '创建您自己的案例研究',
    'pbl.createSubtitle': '设计适合您课程的定制PBL体验，并与社区分享。',
    'pbl.startCreating': '开始创建',

    // Smart Builder page
    'builder.title': '智能组课件',
    'builder.subtitle': '使用AI辅助和结构化学习目标创建全面的课程计划。',
    'builder.lessonSetup': '课程设置',
    'builder.lessonTitle': '课程标题',
    'builder.titlePlaceholder': '输入您的课程标题...',
    'builder.subject': '学科领域',
    'builder.subjectPlaceholder': '例如：生物学、数学、历史',
    'builder.gradeLevel': '年级',
    'builder.duration': '时长',
    'builder.learningObjectives': '学习目标',
    'builder.objectivesPlaceholder': '学生应该从这节课中学到什么？',
    'builder.keyTopics': '关键主题和概念',
    'builder.topicsPlaceholder': '列出要涵盖的主要主题...',
    'builder.generateLesson': '生成课程计划',
    'builder.lessonPreview': '生成的课程预览',
    'builder.saveLesson': '保存课程',
    'builder.shareLesson': '分享',
    'builder.exportLesson': '导出',
    'builder.templates': '课程模板',
    'builder.viewAllTemplates': '查看所有模板',

    // Analytics page
    'analytics.title': '学习分析',
    'analytics.subtitle': '通过全面的分析和见解跟踪学生进度、参与度和表现。',
    'analytics.totalStudents': '学生总数',
    'analytics.avgEngagement': '平均参与度',
    'analytics.completionRate': '完成率',
    'analytics.avgTime': '平均会话时间',
    'analytics.classPerformance': '班级表现概览',
    'analytics.students': '名学生',
    'analytics.engagement': '参与度',
    'analytics.completion': '完成度',
    'analytics.topPerformers': '优秀表现者',
    'analytics.skillsDevelopment': '技能发展跟踪',
    'analytics.criticalThinking': '批判性思维',
    'analytics.collaboration': '协作能力',
    'analytics.problemSolving': '问题解决',

    // Classroom page
    'classroom.title': '班级管理',
    'classroom.subtitle': '使用全面的管理工具管理您的班级、学生和学习小组。',
    'classroom.addStudent': '添加学生',
    'classroom.takeAttendance': '考勤',
    'classroom.sendMessage': '发送消息',
    'classroom.classSettings': '班级设置',
    'classroom.myClasses': '我的班级',
    'classroom.students': '名学生',
    'classroom.active': '活跃',
    'classroom.attendance': '出勤率',
    'classroom.assignments': '活跃作业',
    'classroom.viewClass': '查看班级',
    'classroom.contact': '联系',
    'classroom.recentActivity': '最近学生活动',
    'classroom.learningGroups': '学习小组',
    'classroom.manageGroups': '管理小组',
    'classroom.quickStats': '快速统计',
    'classroom.totalStudents': '学生总数',
    'classroom.avgAttendance': '平均出勤率',
    'classroom.activeAssignments': '活跃作业',
  }
};

export const LanguageProvider = ({ children }: LanguageProviderProps) => {
  const [language, setLanguageState] = useState<Language>('en');

  // Auto-detect browser language on first load
  useEffect(() => {
    const savedLanguage = localStorage.getItem('userLanguage') as Language;
    if (savedLanguage === 'en' || savedLanguage === 'zh') {
      setLanguageState(savedLanguage);
    } else {
      // Auto-detect browser language
      const browserLanguage = navigator.language.toLowerCase();
      if (browserLanguage.startsWith('zh')) {
        setLanguageState('zh');
      } else {
        setLanguageState('en');
      }
    }
  }, []);

  // Save language to localStorage whenever it changes
  const setLanguage = (newLanguage: Language) => {
    setLanguageState(newLanguage);
    localStorage.setItem('userLanguage', newLanguage);
  };

  // Translation function
  const t = (key: string) => {
    return translations[language][key] || key;
  };

  return (
    <LanguageContext.Provider value={{ language, setLanguage, t }}>
      {children}
    </LanguageContext.Provider>
  );
};
